<?php
namespace common\models;

/**
 * redis连接类
 * @author huqq
 *
 */
class RedisConnecter
{
    private static $CONN_TIMEOUT = 3;
    private static $connect_pool = array();
    public static function connRedis($instance, $ismaster = true)
    {
        $redis_config = \Yii::$app->redis->conf;

        if (empty($redis_config)) {
            return false;
        }
        
        $conf = array();
        $password = "";
        if ($ismaster === true){
            $conf = $redis_config[$instance]['master'];
            $password = $conf['password'];
        } else {
            $slave_info = $redis_config[$instance]['slave'];
            $password = $slave_info['password'];
            $list = $slave_info['list'];
            $rand_key = array_rand($list);
            $conf = $list[$rand_key];
        }
        $host = $conf['host'];
        $db = $conf['database'];
        $port = $conf['port'];

        if (isset(self::$connect_pool[$instance]) && empty($_SERVER['is_daemon'])) {
            // 除了daemon进程，同一个请求多次连接实例时，可重复使用上一次的连接资源
            return self::$connect_pool[$instance];
        }
        
        $redis_obj = new \Redis();
        $tmp_count = 0;
        $conn_sec = FALSE;
        // 3次失败重连机制
        while ($tmp_count < 3 and $conn_sec === FALSE) {
            $tmp_count = $tmp_count + 1;
            try {
                if ($redis_obj->connect($host, $port, self::$CONN_TIMEOUT)) {
                    if (!empty($password)) {
                        $redis_obj->auth($password);
                    }
                    if ($db > 0) {
                        $conn_sec = $redis_obj->SELECT($db);
                    } else {
                        $conn_sec = TRUE;
                    }
                } else {
                    $conn_sec = FALSE;
                }
            } catch (\RedisException $e) {
                $conn_sec = FALSE;
            }
        }
        
        //if ($redis_obj instanceof \Redis and isset($redis_obj->socket)) {
        if ($redis_obj instanceof \Redis) {
            self::$connect_pool[$instance] = $redis_obj;
            return $redis_obj;
        }
        return FALSE;
    }
}